package org.example.tlias.handle;


import org.example.tlias.pojo.Result;
import org.example.tlias.exception.BaseException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import org.example.tlias.constant.MessageConstant;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler
    public Result error(BaseException ex) {
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result error(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String msg = split[2] + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

}
